import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import sys
import os
import numpy as np

# 添加src到路径
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'src'))

# 页面配置已在主应用中设置

# 样式配置
st.markdown("""
<style>
    .metric-card {
        background-color: #f0f2f6;
        padding: 1.5rem;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .financial-card {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 1rem;
        margin: 0.5rem 0;
        background-color: #fafafa;
    }
    .positive { color: #4caf50; }
    .negative { color: #f44336; }
    .neutral { color: #ff9800; }
</style>
""", unsafe_allow_html=True)

# 页面标题
st.markdown('<div style="font-size: 2.5rem; font-weight: bold; color: #1f77b4; text-align: center; margin-bottom: 2rem;">💰 财务管理系统</div>', unsafe_allow_html=True)

# 侧边栏功能选择
st.sidebar.title("功能菜单")
function = st.sidebar.selectbox(
    "选择功能",
    ["📊 财务概览", "💳 应收账款", "💸 应付账款", "📈 成本分析", "💹 预算管理", "📋 财务报表", "🔍 财务分析"]
)

# 财务概览
if function == "📊 财务概览":
    st.header("财务概览")
    
    # 关键财务指标
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.metric("总收入", "¥12.5M", "¥2.3M")
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col2:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.metric("总成本", "¥8.9M", "¥1.2M")
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col3:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.metric("净利润", "¥3.6M", "¥1.1M")
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col4:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.metric("利润率", "28.8%", "3.2%")
        st.markdown('</div>', unsafe_allow_html=True)
    
    st.markdown("---")
    
    # 现金流概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("现金余额", "¥5.2M", "¥0.8M")
    with col2:
        st.metric("应收账款", "¥3.8M", "-¥0.5M")
    with col3:
        st.metric("应付账款", "¥2.1M", "¥0.3M")
    with col4:
        st.metric("净现金流", "¥1.9M", "¥0.6M")
    
    st.markdown("---")
    
    # 财务趋势图表
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("收入与成本趋势")
        
        # 生成月度数据
        months = pd.date_range(start='2024-01-01', end='2024-12-31', freq='M')
        financial_trend = pd.DataFrame({
            '月份': months,
            '收入': [1000000 + i*50000 + np.random.randint(-100000, 200000) for i in range(len(months))],
            '成本': [700000 + i*30000 + np.random.randint(-50000, 100000) for i in range(len(months))]
        })
        financial_trend['利润'] = financial_trend['收入'] - financial_trend['成本']
        
        fig_trend = go.Figure()
        fig_trend.add_trace(go.Scatter(x=financial_trend['月份'], y=financial_trend['收入'], 
                                     mode='lines+markers', name='收入', line=dict(color='#2E8B57')))
        fig_trend.add_trace(go.Scatter(x=financial_trend['月份'], y=financial_trend['成本'], 
                                     mode='lines+markers', name='成本', line=dict(color='#DC143C')))
        fig_trend.add_trace(go.Scatter(x=financial_trend['月份'], y=financial_trend['利润'], 
                                     mode='lines+markers', name='利润', line=dict(color='#4169E1')))
        
        fig_trend.update_layout(title="月度收入成本趋势", xaxis_title="月份", yaxis_title="金额(元)")
        st.plotly_chart(fig_trend, use_container_width=True)
    
    with col2:
        st.subheader("成本结构分析")
        
        cost_structure = pd.DataFrame({
            '成本类型': ['原材料成本', '人工成本', '制造费用', '管理费用', '销售费用', '财务费用'],
            '金额': [3500000, 2100000, 1800000, 900000, 600000, 200000],
            '占比': [39.3, 23.6, 20.2, 10.1, 6.7, 2.2]
        })
        
        fig_cost = px.pie(cost_structure, values='金额', names='成本类型', 
                         title="成本结构分布")
        st.plotly_chart(fig_cost, use_container_width=True)
    
    # 财务健康度指标
    st.subheader("财务健康度指标")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.markdown("**流动性指标**")
        st.metric("流动比率", "2.35", "0.15")
        st.metric("速动比率", "1.87", "0.12")
        st.metric("现金比率", "0.95", "0.08")
    
    with col2:
        st.markdown("**盈利能力指标**")
        st.metric("毛利率", "42.5%", "2.8%")
        st.metric("净利率", "28.8%", "3.2%")
        st.metric("ROE", "18.6%", "2.1%")
    
    with col3:
        st.markdown("**运营效率指标**")
        st.metric("应收账款周转率", "8.5", "0.8")
        st.metric("存货周转率", "6.2", "0.5")
        st.metric("总资产周转率", "1.3", "0.1")
    
    # 预警信息
    st.subheader("财务预警")
    
    warnings = [
        {"类型": "应收账款", "内容": "客户ABC公司账款逾期30天，金额¥450,000", "级别": "高"},
        {"类型": "现金流", "内容": "预计下月现金流缺口¥200,000", "级别": "中"},
        {"类型": "成本控制", "内容": "原材料成本较预算超支8.5%", "级别": "中"},
        {"类型": "预算执行", "内容": "销售费用执行率已达95%", "级别": "低"}
    ]
    
    for warning in warnings:
        if warning["级别"] == "高":
            st.error(f"🚨 **{warning['类型']}**: {warning['内容']}")
        elif warning["级别"] == "中":
            st.warning(f"⚠️ **{warning['类型']}**: {warning['内容']}")
        else:
            st.info(f"ℹ️ **{warning['类型']}**: {warning['内容']}")

# 应收账款管理
elif function == "💳 应收账款":
    st.header("应收账款管理")
    
    # 应收账款概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("应收账款总额", "¥3.8M", "-¥0.5M")
    with col2:
        st.metric("逾期账款", "¥0.8M", "¥0.2M")
    with col3:
        st.metric("逾期率", "21.1%", "3.2%")
    with col4:
        st.metric("平均回款天数", "45天", "-3天")
    
    st.markdown("---")
    
    # 应收账款明细
    st.subheader("应收账款明细")
    
    # 筛选条件
    col1, col2, col3 = st.columns(3)
    with col1:
        customer_filter = st.selectbox("客户筛选", ['全部', '华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团'])
    with col2:
        status_filter = st.selectbox("状态筛选", ['全部', '未到期', '逾期1-30天', '逾期31-60天', '逾期60天以上'])
    with col3:
        amount_filter = st.selectbox("金额筛选", ['全部', '10万以下', '10-50万', '50-100万', '100万以上'])
    
    # 应收账款数据
    receivables_data = pd.DataFrame({
        '客户名称': ['华为技术', '小米科技', '比亚迪', '宁德时代', '美的集团', '格力电器', '海尔集团', '联想集团'],
        '发票号码': [f'INV{datetime.now().strftime("%Y%m")}{i:04d}' for i in range(1, 9)],
        '发票日期': [datetime.now() - timedelta(days=i*15) for i in range(8)],
        '到期日期': [datetime.now() - timedelta(days=i*15) + timedelta(days=30) for i in range(8)],
        '应收金额': [450000, 320000, 680000, 280000, 150000, 520000, 380000, 220000],
        '已收金额': [0, 320000, 480000, 280000, 150000, 0, 380000, 0],
        '未收金额': [450000, 0, 200000, 0, 0, 520000, 0, 220000],
        '逾期天数': [15, 0, 5, 0, 0, 25, 0, 8],
        '状态': ['逾期', '已收款', '逾期', '已收款', '已收款', '逾期', '已收款', '逾期'],
        '跟进人': ['张三', '李四', '王五', '张三', '李四', '王五', '张三', '李四']
    })
    
    st.dataframe(receivables_data, use_container_width=True, height=300)
    
    # 账龄分析
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("账龄分析")
        
        aging_data = pd.DataFrame({
            '账龄区间': ['未到期', '1-30天', '31-60天', '61-90天', '90天以上'],
            '金额': [2200000, 800000, 450000, 250000, 100000],
            '占比': [57.9, 21.1, 11.8, 6.6, 2.6]
        })
        
        fig_aging = px.bar(aging_data, x='账龄区间', y='金额', 
                          title="应收账款账龄分布",
                          color='金额',
                          color_continuous_scale='Reds')
        st.plotly_chart(fig_aging, use_container_width=True)
    
    with col2:
        st.subheader("客户欠款排名")
        
        customer_ranking = receivables_data.groupby('客户名称')['未收金额'].sum().sort_values(ascending=False).head(5)
        customer_ranking_df = pd.DataFrame({
            '客户': customer_ranking.index,
            '欠款金额': customer_ranking.values
        })
        
        fig_ranking = px.bar(customer_ranking_df, x='客户', y='欠款金额',
                           title="客户欠款金额排名")
        fig_ranking.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_ranking, use_container_width=True)
    
    # 催收管理
    st.subheader("催收管理")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("**催收任务**")
        
        collection_tasks = pd.DataFrame({
            '客户': ['华为技术', '格力电器', '联想集团'],
            '逾期金额': [450000, 520000, 220000],
            '逾期天数': [15, 25, 8],
            '催收方式': ['电话催收', '上门催收', '邮件催收'],
            '负责人': ['张三', '王五', '李四'],
            '下次跟进': ['2024-01-15', '2024-01-16', '2024-01-17']
        })
        
        st.dataframe(collection_tasks, use_container_width=True, height=200)
    
    with col2:
        st.markdown("**催收记录**")
        
        collection_records = pd.DataFrame({
            '日期': ['2024-01-10', '2024-01-08', '2024-01-05'],
            '客户': ['华为技术', '格力电器', '联想集团'],
            '催收方式': ['电话', '邮件', '上门'],
            '结果': ['承诺本周付款', '需要审批', '部分付款'],
            '跟进人': ['张三', '王五', '李四']
        })
        
        st.dataframe(collection_records, use_container_width=True, height=200)
    
    # 操作按钮
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("生成催收函"):
            st.success("催收函已生成")
    with col2:
        if st.button("批量催收"):
            st.success("批量催收任务已创建")
    with col3:
        if st.button("导出应收明细"):
            st.success("应收账款明细已导出")

# 应付账款管理
elif function == "💸 应付账款":
    st.header("应付账款管理")
    
    # 应付账款概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("应付账款总额", "¥2.1M", "¥0.3M")
    with col2:
        st.metric("本月到期", "¥0.6M", "¥0.1M")
    with col3:
        st.metric("逾期未付", "¥0.2M", "-¥0.05M")
    with col4:
        st.metric("平均付款天数", "28天", "2天")
    
    st.markdown("---")
    
    # 应付账款明细
    st.subheader("应付账款明细")
    
    # 筛选条件
    col1, col2, col3 = st.columns(3)
    with col1:
        supplier_filter = st.selectbox("供应商筛选", ['全部', '华东化工', '南方包装', '北京设备', '上海物流', '广州原料'])
    with col2:
        status_filter = st.selectbox("状态筛选", ['全部', '未到期', '即将到期', '已逾期'])
    with col3:
        type_filter = st.selectbox("类型筛选", ['全部', '货款', '服务费', '设备款', '其他'])
    
    # 应付账款数据
    payables_data = pd.DataFrame({
        '供应商名称': ['华东化工', '南方包装', '北京设备', '上海物流', '广州原料', '东北钢铁', '西南电力', '华南运输'],
        '发票号码': [f'PINV{datetime.now().strftime("%Y%m")}{i:04d}' for i in range(1, 9)],
        '发票日期': [datetime.now() - timedelta(days=i*10) for i in range(8)],
        '到期日期': [datetime.now() - timedelta(days=i*10) + timedelta(days=45) for i in range(8)],
        '应付金额': [280000, 150000, 420000, 180000, 320000, 250000, 190000, 160000],
        '已付金额': [280000, 0, 220000, 180000, 0, 250000, 190000, 0],
        '未付金额': [0, 150000, 200000, 0, 320000, 0, 0, 160000],
        '账款类型': ['货款', '包装费', '设备款', '运费', '货款', '原料款', '电费', '运费'],
        '状态': ['已付款', '未到期', '未到期', '已付款', '即将到期', '已付款', '已付款', '未到期'],
        '负责人': ['张三', '李四', '王五', '张三', '李四', '王五', '张三', '李四']
    })
    
    st.dataframe(payables_data, use_container_width=True, height=300)
    
    # 付款计划
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("付款计划")
        
        payment_plan = pd.DataFrame({
            '付款日期': [datetime.now() + timedelta(days=i*7) for i in range(4)],
            '供应商': ['南方包装', '北京设备', '广州原料', '华南运输'],
            '付款金额': [150000, 200000, 320000, 160000],
            '付款方式': ['银行转账', '承兑汇票', '银行转账', '现金'],
            '状态': ['待审批', '已审批', '待审批', '待审批']
        })
        
        st.dataframe(payment_plan, use_container_width=True, height=200)
    
    with col2:
        st.subheader("供应商付款统计")
        
        supplier_payment = payables_data.groupby('供应商名称')['未付金额'].sum().sort_values(ascending=False)
        supplier_payment_df = pd.DataFrame({
            '供应商': supplier_payment.index,
            '未付金额': supplier_payment.values
        })
        
        fig_supplier = px.bar(supplier_payment_df, x='供应商', y='未付金额',
                            title="供应商未付款统计")
        fig_supplier.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_supplier, use_container_width=True)
    
    # 现金流预测
    st.subheader("现金流预测")
    
    # 生成未来30天的现金流预测
    future_dates = pd.date_range(start=datetime.now(), periods=30, freq='D')
    cash_flow_forecast = pd.DataFrame({
        '日期': future_dates,
        '应付款项': [np.random.randint(0, 200000) if np.random.random() > 0.7 else 0 for _ in range(30)],
        '应收款项': [np.random.randint(0, 300000) if np.random.random() > 0.8 else 0 for _ in range(30)]
    })
    
    cash_flow_forecast['净现金流'] = cash_flow_forecast['应收款项'] - cash_flow_forecast['应付款项']
    cash_flow_forecast['累计现金流'] = cash_flow_forecast['净现金流'].cumsum() + 5200000  # 初始现金5.2M
    
    fig_forecast = go.Figure()
    fig_forecast.add_trace(go.Scatter(x=cash_flow_forecast['日期'], y=cash_flow_forecast['累计现金流'],
                                    mode='lines', name='累计现金流', line=dict(color='#2E8B57')))
    fig_forecast.add_hline(y=1000000, line_dash="dash", line_color="red", 
                          annotation_text="最低现金余额警戒线")
    
    fig_forecast.update_layout(title="未来30天现金流预测", xaxis_title="日期", yaxis_title="现金余额(元)")
    st.plotly_chart(fig_forecast, use_container_width=True)
    
    # 操作按钮
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("创建付款申请"):
            st.success("付款申请已创建")
    with col2:
        if st.button("批量付款"):
            st.success("批量付款任务已提交")
    with col3:
        if st.button("导出应付明细"):
            st.success("应付账款明细已导出")

# 成本分析
elif function == "📈 成本分析":
    st.header("成本分析")
    
    # 成本概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("总成本", "¥8.9M", "¥1.2M")
    with col2:
        st.metric("单位成本", "¥89.5", "¥5.2")
    with col3:
        st.metric("成本率", "71.2%", "-3.2%")
    with col4:
        st.metric("成本节约", "¥0.8M", "¥0.3M")
    
    st.markdown("---")
    
    # 成本结构分析
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("成本结构分析")
        
        cost_structure = pd.DataFrame({
            '成本类型': ['直接材料', '直接人工', '制造费用', '管理费用', '销售费用', '财务费用'],
            '本期金额': [3500000, 2100000, 1800000, 900000, 600000, 200000],
            '上期金额': [3200000, 2000000, 1700000, 850000, 580000, 180000],
            '变动额': [300000, 100000, 100000, 50000, 20000, 20000],
            '变动率': [9.4, 5.0, 5.9, 5.9, 3.4, 11.1]
        })
        
        fig_structure = px.bar(cost_structure, x='成本类型', y=['本期金额', '上期金额'],
                             title="成本结构对比分析", barmode='group')
        fig_structure.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_structure, use_container_width=True)
    
    with col2:
        st.subheader("成本占比分析")
        
        fig_pie = px.pie(cost_structure, values='本期金额', names='成本类型',
                        title="本期成本结构占比")
        st.plotly_chart(fig_pie, use_container_width=True)
    
    # 产品成本分析
    st.subheader("产品成本分析")
    
    product_cost = pd.DataFrame({
        '产品名称': ['产品A', '产品B', '产品C', '产品D', '产品E'],
        '生产数量': [1000, 800, 1200, 600, 900],
        '直接材料': [450000, 320000, 480000, 240000, 360000],
        '直接人工': [180000, 160000, 240000, 120000, 180000],
        '制造费用': [120000, 100000, 150000, 75000, 112500],
        '总成本': [750000, 580000, 870000, 435000, 652500],
        '单位成本': [750, 725, 725, 725, 725]
    })
    
    st.dataframe(product_cost, use_container_width=True, height=300)
    
    # 成本趋势分析
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("月度成本趋势")
        
        months = pd.date_range(start='2024-01-01', end='2024-12-31', freq='M')
        monthly_cost = pd.DataFrame({
            '月份': months,
            '直接材料': [300000 + i*10000 + np.random.randint(-20000, 30000) for i in range(len(months))],
            '直接人工': [180000 + i*5000 + np.random.randint(-10000, 15000) for i in range(len(months))],
            '制造费用': [150000 + i*3000 + np.random.randint(-8000, 12000) for i in range(len(months))]
        })
        
        fig_trend = px.line(monthly_cost, x='月份', y=['直接材料', '直接人工', '制造费用'],
                          title="月度成本趋势")
        st.plotly_chart(fig_trend, use_container_width=True)
    
    with col2:
        st.subheader("成本控制效果")
        
        control_effect = pd.DataFrame({
            '控制措施': ['原料采购优化', '生产效率提升', '能耗管理', '人员优化', '设备维护'],
            '节约金额': [150000, 120000, 80000, 100000, 60000],
            '实施状态': ['已完成', '进行中', '已完成', '已完成', '计划中']
        })
        
        fig_control = px.bar(control_effect, x='控制措施', y='节约金额',
                           title="成本控制措施效果",
                           color='实施状态')
        fig_control.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_control, use_container_width=True)
    
    # 成本预算对比
    st.subheader("成本预算执行情况")
    
    budget_comparison = pd.DataFrame({
        '成本项目': ['直接材料', '直接人工', '制造费用', '管理费用', '销售费用'],
        '预算金额': [3200000, 2000000, 1600000, 800000, 500000],
        '实际金额': [3500000, 2100000, 1800000, 900000, 600000],
        '差异金额': [300000, 100000, 200000, 100000, 100000],
        '执行率': [109.4, 105.0, 112.5, 112.5, 120.0]
    })
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.dataframe(budget_comparison, use_container_width=True, height=250)
    
    with col2:
        fig_budget = px.bar(budget_comparison, x='成本项目', y=['预算金额', '实际金额'],
                          title="预算vs实际成本对比", barmode='group')
        fig_budget.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_budget, use_container_width=True)

# 预算管理
elif function == "💹 预算管理":
    st.header("预算管理")
    
    # 预算执行概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("年度预算", "¥15.0M", "¥2.0M")
    with col2:
        st.metric("已执行", "¥11.2M", "¥1.8M")
    with col3:
        st.metric("执行率", "74.7%", "5.2%")
    with col4:
        st.metric("剩余预算", "¥3.8M", "-¥1.8M")
    
    st.markdown("---")
    
    # 预算执行明细
    st.subheader("预算执行明细")
    
    budget_detail = pd.DataFrame({
        '预算科目': ['销售收入', '直接材料', '直接人工', '制造费用', '管理费用', '销售费用', '财务费用', '研发费用'],
        '年度预算': [15000000, -4000000, -2500000, -2000000, -1200000, -800000, -300000, -1000000],
        '已执行': [12500000, -3500000, -2100000, -1800000, -900000, -600000, -200000, -750000],
        '执行率': [83.3, 87.5, 84.0, 90.0, 75.0, 75.0, 66.7, 75.0],
        '剩余预算': [2500000, -500000, -400000, -200000, -300000, -200000, -100000, -250000],
        '预计完成率': [95.0, 92.0, 88.0, 95.0, 85.0, 85.0, 80.0, 90.0]
    })
    
    # 格式化显示
    def format_currency(val):
        if val < 0:
            return f"-¥{abs(val):,.0f}"
        else:
            return f"¥{val:,.0f}"
    
    display_budget = budget_detail.copy()
    for col in ['年度预算', '已执行', '剩余预算']:
        display_budget[col] = display_budget[col].apply(format_currency)
    
    display_budget['执行率'] = display_budget['执行率'].apply(lambda x: f"{x:.1f}%")
    display_budget['预计完成率'] = display_budget['预计完成率'].apply(lambda x: f"{x:.1f}%")
    
    st.dataframe(display_budget, use_container_width=True, height=300)
    
    # 预算执行图表
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("预算执行率分析")
        
        fig_execution = px.bar(budget_detail, x='预算科目', y='执行率',
                             title="各科目预算执行率",
                             color='执行率',
                             color_continuous_scale='RdYlGn')
        fig_execution.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_execution, use_container_width=True)
    
    with col2:
        st.subheader("预算vs实际对比")
        
        # 只显示支出项目
        expense_budget = budget_detail[budget_detail['年度预算'] < 0].copy()
        expense_budget['年度预算'] = expense_budget['年度预算'].abs()
        expense_budget['已执行'] = expense_budget['已执行'].abs()
        
        fig_comparison = px.bar(expense_budget, x='预算科目', y=['年度预算', '已执行'],
                              title="支出预算vs实际对比", barmode='group')
        fig_comparison.update_layout(xaxis_tickangle=45)
        st.plotly_chart(fig_comparison, use_container_width=True)
    
    # 预算调整申请
    st.subheader("预算调整申请")
    
    with st.expander("提交预算调整申请"):
        with st.form("budget_adjustment_form"):
            col1, col2 = st.columns(2)
            
            with col1:
                adjustment_type = st.selectbox("调整类型", ['预算增加', '预算减少', '科目调整'])
                budget_item = st.selectbox("预算科目", budget_detail['预算科目'].tolist())
                adjustment_amount = st.number_input("调整金额", min_value=0, step=1000)
            
            with col2:
                adjustment_reason = st.text_area("调整原因")
                applicant = st.text_input("申请人", value="当前用户")
                expected_date = st.date_input("期望生效日期", datetime.now())
            
            submitted = st.form_submit_button("提交申请")
            
            if submitted:
                if budget_item and adjustment_amount > 0 and adjustment_reason:
                    st.success(f"预算调整申请已提交：{budget_item} {adjustment_type} ¥{adjustment_amount:,.0f}")
                else:
                    st.error("请填写所有必填字段")
    
    # 预算预警
    st.subheader("预算预警")
    
    warnings = [
        {"科目": "制造费用", "执行率": "90.0%", "预警级别": "高", "建议": "建议控制制造费用支出"},
        {"科目": "直接材料", "执行率": "87.5%", "预警级别": "中", "建议": "关注原材料价格波动"},
        {"科目": "销售费用", "执行率": "75.0%", "预警级别": "低", "建议": "可适当增加市场投入"}
    ]
    
    for warning in warnings:
        if warning["预警级别"] == "高":
            st.error(f"🚨 **{warning['科目']}** 执行率已达 {warning['执行率']}，{warning['建议']}")
        elif warning["预警级别"] == "中":
            st.warning(f"⚠️ **{warning['科目']}** 执行率已达 {warning['执行率']}，{warning['建议']}")
        else:
            st.info(f"ℹ️ **{warning['科目']}** 执行率 {warning['执行率']}，{warning['建议']}")

# 财务报表
elif function == "📋 财务报表":
    st.header("财务报表")
    
    # 报表类型选择
    report_type = st.selectbox("选择报表类型", 
                              ["资产负债表", "利润表", "现金流量表", "财务分析报表"])
    
    # 时间范围选择
    col1, col2 = st.columns(2)
    with col1:
        start_date = st.date_input("开始日期", datetime.now().replace(month=1, day=1))
    with col2:
        end_date = st.date_input("结束日期", datetime.now())
    
    if report_type == "资产负债表":
        st.subheader("资产负债表")
        
        balance_sheet = pd.DataFrame({
            '项目': [
                '流动资产', '货币资金', '应收账款', '存货', '其他流动资产',
                '非流动资产', '固定资产', '无形资产', '长期投资',
                '资产总计', '',
                '流动负债', '应付账款', '短期借款', '其他流动负债',
                '非流动负债', '长期借款', '递延税款',
                '负债合计', '',
                '所有者权益', '实收资本', '资本公积', '盈余公积', '未分配利润',
                '所有者权益合计', '',
                '负债和所有者权益总计'
            ],
            '本期金额': [
                '', 5200000, 3800000, 4500000, 800000,
                '', 8000000, 1200000, 2000000,
                25500000, '',
                '', 2100000, 3000000, 500000,
                '', 5000000, 300000,
                10900000, '',
                '', 8000000, 2000000, 1500000, 3100000,
                14600000, '',
                25500000
            ],
            '上期金额': [
                '', 4800000, 4200000, 4200000, 700000,
                '', 7500000, 1100000, 1800000,
                24300000, '',
                '', 2300000, 3200000, 400000,
                '', 4800000, 250000,
                10950000, '',
                '', 8000000, 2000000, 1200000, 2150000,
                13350000, '',
                24300000
            ]
        })
        
        # 格式化显示
        def format_balance_sheet(val):
            if val == '' or pd.isna(val):
                return ''
            return f"¥{val:,.0f}"
        
        display_balance = balance_sheet.copy()
        display_balance['本期金额'] = display_balance['本期金额'].apply(format_balance_sheet)
        display_balance['上期金额'] = display_balance['上期金额'].apply(format_balance_sheet)
        
        st.dataframe(display_balance, use_container_width=True, height=400)
    
    elif report_type == "利润表":
        st.subheader("利润表")
        
        income_statement = pd.DataFrame({
            '项目': [
                '营业收入', '减：营业成本', '毛利润',
                '减：销售费用', '减：管理费用', '减：财务费用',
                '营业利润', '加：营业外收入', '减：营业外支出',
                '利润总额', '减：所得税费用', '净利润'
            ],
            '本期金额': [
                12500000, -8900000, 3600000,
                -600000, -900000, -200000,
                1900000, 50000, -20000,
                1930000, -480000, 1450000
            ],
            '上期金额': [
                10200000, -7700000, 2500000,
                -580000, -850000, -180000,
                890000, 30000, -15000,
                905000, -225000, 680000
            ],
            '增减额': [
                2300000, -1200000, 1100000,
                -20000, -50000, -20000,
                1010000, 20000, -5000,
                1025000, -255000, 770000
            ]
        })
        
        # 格式化显示
        def format_income(val):
            if val < 0:
                return f"-¥{abs(val):,.0f}"
            else:
                return f"¥{val:,.0f}"
        
        display_income = income_statement.copy()
        for col in ['本期金额', '上期金额', '增减额']:
            display_income[col] = display_income[col].apply(format_income)
        
        st.dataframe(display_income, use_container_width=True, height=400)
    
    elif report_type == "现金流量表":
        st.subheader("现金流量表")
        
        cash_flow = pd.DataFrame({
            '项目': [
                '经营活动现金流量：',
                '销售商品收到的现金', '购买商品支付的现金', '支付职工薪酬',
                '支付的各项税费', '其他经营活动现金',
                '经营活动现金流量净额', '',
                '投资活动现金流量：',
                '购建固定资产支付的现金', '投资支付的现金',
                '投资活动现金流量净额', '',
                '筹资活动现金流量：',
                '借款收到的现金', '偿还债务支付的现金', '支付利息',
                '筹资活动现金流量净额', '',
                '现金及现金等价物净增加额',
                '期初现金及现金等价物余额',
                '期末现金及现金等价物余额'
            ],
            '本期金额': [
                '',
                11800000, -8200000, -2100000,
                -480000, -120000,
                900000, '',
                '',
                -500000, -200000,
                -700000, '',
                '',
                1000000, -800000, -200000,
                0, '',
                200000,
                5000000,
                5200000
            ]
        })
        
        # 格式化显示
        def format_cash_flow(val):
            if val == '' or pd.isna(val):
                return ''
            if val < 0:
                return f"-¥{abs(val):,.0f}"
            else:
                return f"¥{val:,.0f}"
        
        display_cash = cash_flow.copy()
        display_cash['本期金额'] = display_cash['本期金额'].apply(format_cash_flow)
        
        st.dataframe(display_cash, use_container_width=True, height=400)
    
    elif report_type == "财务分析报表":
        st.subheader("财务分析报表")
        
        # 财务比率分析
        financial_ratios = pd.DataFrame({
            '指标类别': [
                '偿债能力', '偿债能力', '偿债能力',
                '营运能力', '营运能力', '营运能力',
                '盈利能力', '盈利能力', '盈利能力',
                '发展能力', '发展能力', '发展能力'
            ],
            '财务指标': [
                '流动比率', '速动比率', '资产负债率',
                '应收账款周转率', '存货周转率', '总资产周转率',
                '毛利率', '净利率', '净资产收益率',
                '营业收入增长率', '净利润增长率', '总资产增长率'
            ],
            '本期数值': [
                2.35, 1.87, 42.7,
                8.5, 6.2, 1.3,
                28.8, 11.6, 9.9,
                22.5, 113.2, 4.9
            ],
            '上期数值': [
                2.20, 1.75, 45.1,
                7.7, 5.7, 1.2,
                24.5, 6.7, 5.1,
                15.2, 25.8, 8.2
            ],
            '行业平均': [
                2.1, 1.6, 48.0,
                7.2, 5.8, 1.1,
                25.0, 8.5, 7.2,
                18.0, 45.0, 6.0
            ],
            '评价': [
                '良好', '良好', '优秀',
                '优秀', '良好', '良好',
                '优秀', '优秀', '优秀',
                '优秀', '优秀', '一般'
            ]
        })
        
        st.dataframe(financial_ratios, use_container_width=True, height=350)
        
        # 财务指标趋势图
        col1, col2 = st.columns(2)
        
        with col1:
            profitability = financial_ratios[financial_ratios['指标类别'] == '盈利能力']
            fig_profit = px.bar(profitability, x='财务指标', y=['本期数值', '上期数值', '行业平均'],
                              title="盈利能力指标对比", barmode='group')
            fig_profit.update_layout(xaxis_tickangle=45)
            st.plotly_chart(fig_profit, use_container_width=True)
        
        with col2:
            operation = financial_ratios[financial_ratios['指标类别'] == '营运能力']
            fig_operation = px.bar(operation, x='财务指标', y=['本期数值', '上期数值', '行业平均'],
                                 title="营运能力指标对比", barmode='group')
            fig_operation.update_layout(xaxis_tickangle=45)
            st.plotly_chart(fig_operation, use_container_width=True)
    
    # 导出功能
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("导出Excel"):
            st.success(f"{report_type}已导出为Excel文件")
    with col2:
        if st.button("导出PDF"):
            st.success(f"{report_type}已导出为PDF文件")
    with col3:
        if st.button("发送邮件"):
            st.success(f"{report_type}已发送到指定邮箱")

# 财务分析
elif function == "🔍 财务分析":
    st.header("财务分析")
    
    # 分析类型选择
    analysis_type = st.selectbox("选择分析类型", 
                               ["盈利能力分析", "偿债能力分析", "营运能力分析", "成长能力分析", "综合财务分析"])
    
    if analysis_type == "盈利能力分析":
        st.subheader("盈利能力分析")
        
        # 盈利能力指标
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("毛利率", "28.8%", "4.3%")
        with col2:
            st.metric("净利率", "11.6%", "4.9%")
        with col3:
            st.metric("ROE", "9.9%", "4.8%")
        with col4:
            st.metric("ROA", "5.7%", "2.8%")
        
        # 盈利能力趋势
        col1, col2 = st.columns(2)
        
        with col1:
            months = pd.date_range(start='2024-01-01', end='2024-12-31', freq='M')
            profitability_trend = pd.DataFrame({
                '月份': months,
                '毛利率': [24 + i*0.4 + np.random.uniform(-2, 2) for i in range(len(months))],
                '净利率': [7 + i*0.4 + np.random.uniform(-1, 1) for i in range(len(months))]
            })
            
            fig_trend = px.line(profitability_trend, x='月份', y=['毛利率', '净利率'],
                              title="盈利能力趋势分析")
            st.plotly_chart(fig_trend, use_container_width=True)
        
        with col2:
            # 行业对比
            industry_comparison = pd.DataFrame({
                '指标': ['毛利率', '净利率', 'ROE', 'ROA'],
                '本公司': [28.8, 11.6, 9.9, 5.7],
                '行业平均': [25.0, 8.5, 7.2, 4.1],
                '行业领先': [35.0, 15.0, 12.0, 8.0]
            })
            
            fig_comparison = px.bar(industry_comparison, x='指标', y=['本公司', '行业平均', '行业领先'],
                                  title="盈利能力行业对比", barmode='group')
            st.plotly_chart(fig_comparison, use_container_width=True)
        
        # 盈利能力分析结论
        st.subheader("分析结论")
        
        conclusions = [
            "✅ 毛利率28.8%，高于行业平均水平25.0%，显示产品竞争力较强",
            "✅ 净利率11.6%，明显优于行业平均8.5%，盈利能力突出",
            "✅ ROE 9.9%，超过行业平均7.2%，股东回报良好",
            "⚠️ 建议继续关注成本控制，保持盈利能力优势"
        ]
        
        for conclusion in conclusions:
            if conclusion.startswith("✅"):
                st.success(conclusion)
            else:
                st.warning(conclusion)
    
    elif analysis_type == "偿债能力分析":
        st.subheader("偿债能力分析")
        
        # 偿债能力指标
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("流动比率", "2.35", "0.15")
        with col2:
            st.metric("速动比率", "1.87", "0.12")
        with col3:
            st.metric("资产负债率", "42.7%", "-2.4%")
        with col4:
            st.metric("利息保障倍数", "9.65", "4.05")
        
        # 偿债能力分析图表
        col1, col2 = st.columns(2)
        
        with col1:
            # 流动性指标趋势
            quarters = ['Q1', 'Q2', 'Q3', 'Q4']
            liquidity_trend = pd.DataFrame({
                '季度': quarters,
                '流动比率': [2.1, 2.2, 2.3, 2.35],
                '速动比率': [1.6, 1.7, 1.8, 1.87]
            })
            
            fig_liquidity = px.line(liquidity_trend, x='季度', y=['流动比率', '速动比率'],
                                  title="流动性指标趋势")
            st.plotly_chart(fig_liquidity, use_container_width=True)
        
        with col2:
            # 债务结构分析
            debt_structure = pd.DataFrame({
                '债务类型': ['短期借款', '应付账款', '其他流动负债', '长期借款', '其他长期负债'],
                '金额': [3000000, 2100000, 500000, 5000000, 300000],
                '占比': [27.5, 19.3, 4.6, 45.9, 2.8]
            })
            
            fig_debt = px.pie(debt_structure, values='金额', names='债务类型',
                            title="债务结构分析")
            st.plotly_chart(fig_debt, use_container_width=True)
        
        # 偿债能力评价
        st.subheader("偿债能力评价")
        
        solvency_evaluation = pd.DataFrame({
            '指标': ['流动比率', '速动比率', '资产负债率', '利息保障倍数'],
            '数值': [2.35, 1.87, 42.7, 9.65],
            '标准值': ['≥2.0', '≥1.0', '≤60%', '≥3.0'],
            '评价': ['优秀', '优秀', '良好', '优秀'],
            '风险等级': ['低', '低', '低', '低']
        })
        
        st.dataframe(solvency_evaluation, use_container_width=True, height=300)
    
    elif analysis_type == "营运能力分析":
        st.subheader("营运能力分析")
        
        # 营运能力指标
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("应收账款周转率", "8.5次", "0.8次")
        with col2:
            st.metric("存货周转率", "6.2次", "0.5次")
        with col3:
            st.metric("总资产周转率", "1.3次", "0.1次")
        with col4:
            st.metric("固定资产周转率", "1.56次", "0.18次")
        
        # 周转天数分析
        col1, col2 = st.columns(2)
        
        with col1:
            turnover_days = pd.DataFrame({
                '指标': ['应收账款周转天数', '存货周转天数', '应付账款周转天数', '现金周转周期'],
                '本期': [43, 59, 35, 67],
                '上期': [47, 64, 38, 73],
                '行业平均': [51, 63, 40, 74]
            })
            
            fig_days = px.bar(turnover_days, x='指标', y=['本期', '上期', '行业平均'],
                              title="周转天数对比分析", barmode='group')
            fig_days.update_layout(xaxis_tickangle=45)
            st.plotly_chart(fig_days, use_container_width=True)
        
        with col2:
            # 营运能力趋势
            quarters = ['Q1', 'Q2', 'Q3', 'Q4']
            operation_trend = pd.DataFrame({
                '季度': quarters,
                '应收账款周转率': [7.8, 8.1, 8.3, 8.5],
                '存货周转率': [5.8, 6.0, 6.1, 6.2],
                '总资产周转率': [1.1, 1.2, 1.25, 1.3]
            })
            
            fig_operation = px.line(operation_trend, x='季度', 
                                  y=['应收账款周转率', '存货周转率', '总资产周转率'],
                                  title="营运能力趋势分析")
            st.plotly_chart(fig_operation, use_container_width=True)
        
        # 营运能力评价
        st.subheader("营运能力评价")
        
        operation_evaluation = [
            "✅ 应收账款周转率8.5次，高于行业平均7.2次，回款效率良好",
            "✅ 存货周转率6.2次，略高于行业平均5.8次，库存管理有效",
            "✅ 总资产周转率1.3次，优于行业平均1.1次，资产利用效率较高",
            "💡 建议进一步优化供应链管理，提升整体营运效率"
        ]
        
        for evaluation in operation_evaluation:
            if evaluation.startswith("✅"):
                st.success(evaluation)
            else:
                st.info(evaluation)
    
    elif analysis_type == "成长能力分析":
        st.subheader("成长能力分析")
        
        # 成长能力指标
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("营业收入增长率", "22.5%", "7.3%")
        with col2:
            st.metric("净利润增长率", "113.2%", "88.4%")
        with col3:
            st.metric("总资产增长率", "4.9%", "-3.3%")
        with col4:
            st.metric("净资产增长率", "9.4%", "4.3%")
        
        # 成长趋势分析
        col1, col2 = st.columns(2)
        
        with col1:
            # 收入和利润增长趋势
            years = ['2021', '2022', '2023', '2024']
            growth_trend = pd.DataFrame({
                '年份': years,
                '营业收入增长率': [15.2, 18.6, 20.1, 22.5],
                '净利润增长率': [25.8, 45.2, 78.9, 113.2]
            })
            
            fig_growth = px.line(growth_trend, x='年份', y=['营业收入增长率', '净利润增长率'],
                               title="收入利润增长趋势")
            st.plotly_chart(fig_growth, use_container_width=True)
        
        with col2:
            # 资产增长分析
            asset_growth = pd.DataFrame({
                '资产类型': ['总资产', '流动资产', '固定资产', '净资产'],
                '增长率': [4.9, 8.2, 2.1, 9.4],
                '行业平均': [6.0, 7.5, 3.5, 8.0]
            })
            
            fig_asset = px.bar(asset_growth, x='资产类型', y=['增长率', '行业平均'],
                             title="资产增长率对比", barmode='group')
            st.plotly_chart(fig_asset, use_container_width=True)
        
        # 成长质量分析
        st.subheader("成长质量分析")
        
        growth_quality = pd.DataFrame({
            '指标': ['收入增长质量', '利润增长质量', '现金流增长质量', '市场份额增长'],
            '评分': [85, 92, 78, 88],
            '评价': ['良好', '优秀', '良好', '优秀'],
            '说明': [
                '收入增长主要来自主营业务',
                '利润增长超过收入增长，盈利能力提升',
                '现金流增长略低于利润增长',
                '市场份额持续扩大'
            ]
        })
        
        st.dataframe(growth_quality, use_container_width=True, height=300)
    
    elif analysis_type == "综合财务分析":
        st.subheader("综合财务分析")
        
        # 财务综合评分
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("盈利能力评分", "92分", "8分")
        with col2:
            st.metric("偿债能力评分", "88分", "5分")
        with col3:
            st.metric("营运能力评分", "85分", "6分")
        with col4:
            st.metric("成长能力评分", "90分", "12分")
        
        # 雷达图显示综合能力
        categories = ['盈利能力', '偿债能力', '营运能力', '成长能力', '风险控制']
        scores = [92, 88, 85, 90, 86]
        
        fig_radar = go.Figure()
        fig_radar.add_trace(go.Scatterpolar(
            r=scores,
            theta=categories,
            fill='toself',
            name='本公司'
        ))
        
        # 添加行业平均线
        industry_scores = [75, 80, 78, 72, 82]
        fig_radar.add_trace(go.Scatterpolar(
            r=industry_scores,
            theta=categories,
            fill='toself',
            name='行业平均'
        ))
        
        fig_radar.update_layout(
            polar=dict(
                radialaxis=dict(
                    visible=True,
                    range=[0, 100]
                )
            ),
            title="财务能力雷达图",
            showlegend=True
        )
        
        st.plotly_chart(fig_radar, use_container_width=True)
        
        # SWOT分析
        st.subheader("SWOT财务分析")
        
        col1, col2 = st.columns(2)
        
        with col1:
            st.markdown("**优势 (Strengths)**")
            strengths = [
                "盈利能力强，净利率超过行业平均",
                "偿债能力良好，财务风险较低",
                "成长性突出，业务扩张能力强",
                "现金流稳定，资金周转良好"
            ]
            for strength in strengths:
                st.success(f"✅ {strength}")
            
            st.markdown("**机会 (Opportunities)**")
            opportunities = [
                "市场需求增长，业务拓展空间大",
                "技术升级带来成本优化机会",
                "政策支持有利于行业发展",
                "资本市场融资环境改善"
            ]
            for opportunity in opportunities:
                st.info(f"💡 {opportunity}")
        
        with col2:
            st.markdown("**劣势 (Weaknesses)**")
            weaknesses = [
                "固定资产周转率有待提升",
                "研发投入占比相对较低",
                "国际市场份额有限",
                "供应链集中度较高"
            ]
            for weakness in weaknesses:
                st.warning(f"⚠️ {weakness}")
            
            st.markdown("**威胁 (Threats)**")
            threats = [
                "原材料价格波动风险",
                "汇率变动影响出口业务",
                "竞争加剧压缩利润空间",
                "环保政策趋严增加成本"
            ]
            for threat in threats:
                st.error(f"🚨 {threat}")
        
        # 财务建议
        st.subheader("财务管理建议")
        
        recommendations = [
            {
                "类别": "盈利能力提升",
                "建议": "继续优化产品结构，提高高毛利产品占比；加强成本控制，提升运营效率",
                "优先级": "高"
            },
            {
                "类别": "资金管理优化",
                "建议": "加强应收账款管理，缩短回款周期；优化库存结构，提高资金周转效率",
                "优先级": "中"
            },
            {
                "类别": "风险控制",
                "建议": "建立完善的财务预警机制；分散供应商和客户风险，降低集中度",
                "优先级": "中"
            },
            {
                "类别": "投资决策",
                "建议": "加大研发投入，提升技术竞争力；适度扩大产能，抓住市场机遇",
                "优先级": "高"
            }
        ]
        
        for rec in recommendations:
            if rec["优先级"] == "高":
                st.error(f"🔴 **{rec['类别']}** (优先级: {rec['优先级']})\n{rec['建议']}")
            else:
                st.warning(f"🟡 **{rec['类别']}** (优先级: {rec['优先级']})\n{rec['建议']}")

# 页脚
st.markdown("---")
st.markdown("**财务管理系统** | 精准分析，智慧决策")